#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/7/12 11:28
# @Author : 闫峰
# @File    : sku_change_to_listing_update.py
from datetime import datetime

import pymongo

from utils.mysqlUtils.mongodb_utils import MongoDBLink
import os

from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])
info_path = ensure_path_sep(f"\\logs\\info-{dis_path}.log")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}.log")
if os.path.exists(info_path):
    os.remove(info_path)
if os.path.exists(error_path):
    os.remove(error_path)
if os.path.exists(warning_path):
    os.remove(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class TestA:

    def test_(self):
        """
        产品库更新 引起listing变更
        :return:
        """

        znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")

        id_offset = 0
        count = 0
        while True:
            sql = """
            SELECT id,OldValue,NewValue,AllegroIsUpdated,sku 
            FROM `p_product_skuchange_erpmonitor`
            WHERE FieldType=15 
            AND id >%s
            and AllegroIsUpdated=1
            ORDER BY id 
            limit 1000
            """
            res = znkd_db.fetch_all_tuple(sql, (id_offset,))
            if len(res):
                id_offset = res[-1][0]
                for check_sku in res:
                    count += 1
                    print(f"遍历{count}个")
                    get_listing = """
                    SELECT CustomerId,OrderSourceId, ProductId,SellerSku,CategoryId
                    FROM m_allegro_listing 
                    WHERE sku=%s AND OnlineStatus=1;
                    """
                    listing_list = znkd_db.fetch_all_tuple(get_listing, (check_sku[4],))
                    self.check_listing_list(listing_list)

            else:
                break

    def check_listing_list(self, listing_list):
        znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")
        for listing in listing_list:
            get_is_require = """
            SELECT id FROM m_allegro_attribute 
            WHERE CustomerId=1 
            AND CategoryId=%s 
            AND Required=1 
            AND `Name` = "Weight"
            """
            a = "%Weight%"
            is_require = znkd_db.fetch_all_tuple(get_is_require,(listing[4],))
            if len(is_require):
                INFO.logger.info(f"listing={listing}需要修改")



if __name__ == '__main__':
    TestA().test_()
